import React, {Component} from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';

export default class Main extends Component {
    static propTypes = {
        searchName: PropTypes.string.isRequired
    }
    state = {
        initView: true,
        loading: false,
        users: null,
        errorMsg: null
    }

    // 当组件接收到新的属性时回调
    // https://zh-hans.reactjs.org/docs/react-component.html#shouldcomponentupdate
    componentWillReceiveProps(nextProps) { // 这个方法已经过时了，
    // static getDerivedStateFromProps(nextProps, state) { // 使用这个方法要返回更新的state对象
    //     shouldComponentUpdate(nextProps, nextState) { // 使用这个方法返回 true 或者 false。如果返回true 就会重新render
        const {searchName} = nextProps;

        // 更新状态(请求中)
        this.setState({
            initView: false,
            loading: true,

        })
        // 使用axios发送ajax请求
        const url = `https://api.github.com/search/users?q=${searchName}`;
        axios.get(url)
            .then(resp => {
                // 得到相应数据
                const users = resp.data.items.map((value, index) => {
                    // return {url: value["html_url"], avatarUrl: value["avatar_url"], name: value["login"]}
                    return {url: value.html_url, avatarUrl: value.avatar_url, name: value.login}
                });

                // 更新状态(成功)
                this.setState({loading: false, users});
            })
            .catch(error => {
                // 更新失败
                this.setState({loading: false, errorMsg: error.message});
            });

    }

    render() {
        const {initView, loading, users, errorMsg} = this.state;
        if (initView) {
            return <h2>请输入关键字进行搜索....</h2>
        } else if (loading) {
            return <h2>正在请求中....</h2>
        } else if (errorMsg) {
            return <h2>{errorMsg}</h2>;
        } else {
            {
                return users.map((user, index) => (
                    <div className="row" key={index}>
                        <div className="card">
                            <a href={user.url} target="_blank">
                                <img src={user.avatarUrl}
                                     style={{width: '100px'}}/>
                            </a>
                            <p className="card-text">{user.name}</p>
                        </div>
                    </div>
                ));
            }

        }


    }
};